<template>
  <!-- 添加或修改对话框 -->
  <el-dialog :title="title" :visible.sync="visible" width="990px" append-to-body :close-on-click-modal="false">
    <el-row>
      <el-col :span="24">
        <span style="font-weight: bold;">请求头</span>
        <el-button @click="addAuthorizationHeader" style="margin-left:25px;margin-bottom:15px;" type="primary"
                   size="mini">
          {{authorizationButton}}
        </el-button>
        <el-table v-loading="loading" :data="headers" style="width:100%" height="150" border>
          <el-table-column prop="headerName" label="参数名">
            <template slot-scope="scope">
              <el-input v-model="scope.row.headerName" autocomplete="off" size="small" :disabled="true"/>
            </template>
          </el-table-column>
          <el-table-column prop="headerValue" label="参数值">
            <template slot-scope="scope">
              <el-select v-if="scope.row.isAuthorization === 1" v-model="scope.row.type" style="width: 120px;">
                <el-option
                  v-for="item in authHeaderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-input v-if="scope.row.isAuthorization === 1" v-model="scope.row.headerValue" autocomplete="off"
                        clearable size="small" style="width: 320px;"/>
              <el-input v-if="scope.row.isAuthorization !== 1" v-model="scope.row.headerValue" autocomplete="off"
                        clearable size="small"/>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row v-if="paramsVisible === true">
      <el-col :span="24">
        <span style="font-weight: bold;">请求参数</span>
        <el-table v-loading="loading" :data="params" style="width:100%" height="200" border :empty-text="emptyText">
          <el-table-column prop="paramName" label="参数名">
            <template slot-scope="scope">
              <el-input v-model="scope.row.paramName" autocomplete="off" size="small" :disabled="true"/>
            </template>
          </el-table-column>
          <el-table-column prop="paramValue" label="参数值">
            <template slot-scope="scope">
              <el-input v-model="scope.row.paramValue" autocomplete="off" size="small" placeholder="请输入参数值" clearable/>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row v-if="bodyVisible === true">
      <el-col :span="24">
        <span>请求体</span>
        <code-editor v-model="body"
                     :auto-format="true"
                     :smart-indent="true"
                     theme="dracula"
                     :indent-unit="4"
                     :line-wrap="false"
                     ref="codeEditor">
        </code-editor>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="submitButtonLoading" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    executeRepairApi,
    getExecuteRepairParams
  } from "@/api/hawkeye/repair";
  import {
    executeRepairApiByWorkOrder
  } from "@/api/hawkeye/repairworkorder";
  import {CodeEditor} from "bin-code-editor"

  export default {
    name: "RepairParamsTable",
    components: {CodeEditor},
    props: {},
    data() {
      return {
        title: "脚本参数",
        visible: false,
        paramsVisible: false,
        bodyVisible: false,
        submitButtonLoading: false,
        headers: [],
        params: [],
        body: '{}',
        repairId: null,
        workOrderId: null,
        loading: false,
        emptyText: null,
        isFromWorkOrder: false,
        authorizationButton: '添加Authorization',
        authHeaderOptions: [
          {
            label: "Bearer",
            value: "Bearer"
          }, {
            label: "Basic",
            value: "Basic"
          }
        ],
      };
    },
    created() {
    },
    methods: {
      open(repairId, reqType, isFromWorkOrder, workOrderId) {
        this.submitButtonLoading = false;
        this.repairId = repairId;
        this.workOrderId = workOrderId;
        this.isFromWorkOrder = isFromWorkOrder
        this.emptyText = reqType === 1 ? '暂无参数，GET请求只会解析请求地址中的参数' : '暂无参数，POST请求只会解析请求体中的参数';
        this.paramsVisible = reqType === 1
        this.bodyVisible = reqType !== 1
        this.headers = []
        this.params = []
        this.body = '{}'
        this.authorizationButton = '添加Authorization'
        this.getList();
        this.visible = true;
      },
      getList() {
        this.loading = true;
        getExecuteRepairParams(this.repairId).then(res => {
          this.params = res.data.params || [];
          this.body = res.data.body || '{}';
          this.headers = res.data.headers || [];
          this.loading = false;
        });
      },
      cancel() {
        this.paramsVisible = false
        this.bodyVisible = false
        this.submitButtonLoading = false;
        this.headers = []
        this.params = []
        this.body = '{}'
        this.repairId = null
        this.workOrderId = null
        this.emptyText = null
        this.isFromWorkOrder = false
        this.visible = false;
        this.$emit("cancel");
      },
      addAuthorizationHeader() {
        const findHeader = this.headers.find(e => e.headerName === 'Authorization');
        if (findHeader) {
          const index = this.headers.indexOf(findHeader);
          this.headers.splice(index, index);
          this.authorizationButton = '添加Authorization'
        } else {
          let header = {
            headerName: 'Authorization',
            headerValue: '',
            type: 'Bearer',
            isAuthorization: 1
          }
          this.headers.push(header);
          this.authorizationButton = '移除Authorization'
        }
      },
      submitForm() {

        if (this.body){
          try {
            JSON.parse(this.body);
          } catch (error) {
            this.$message.warning("请输入正确的JSON格式");
            return;
          }
        }
        if (this.headers){
          const findHeader = this.headers.find(e => e.headerName === 'Authorization');
          if (findHeader) {
            if (!findHeader.headerValue){
              this.$modal.msgWarning("Authorization必填！");
              return;
            }
          }
        }

        this.submitButtonLoading = true;
        const loading = this.$loading({
          lock: true,
          text: '执行中,请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        if (this.isFromWorkOrder === true) {
          executeRepairApiByWorkOrder({
            id: this.workOrderId,
            repairApiId: this.repairId,
            headersAsString: JSON.stringify(this.headers),
            paramsAsString: JSON.stringify(this.params),
            bodyAsString: this.body
          }).then(res => {
            if (res.code === 200 && res.data === true) {
              this.$modal.msgSuccess("执行成功,请在修复脚本模块中查看执行日志");
            } else {
              this.$modal.msgError("执行失败,请在修复脚本模块中查看执行日志");
            }
            this.$emit("submitted", res);
          }).finally(() => {
            this.submitButtonLoading = false;
            loading.close();
          });
        } else {
          executeRepairApi({
            id: this.repairId,
            headersAsString: JSON.stringify(this.headers),
            paramsAsString: JSON.stringify(this.params),
            bodyAsString: JSON.stringify(JSON.parse(this.body))
          }).then(res => {
            if (res.code === 200 && res.data === true) {
              this.$modal.msgSuccess("执行成功,请查看日志");
            } else {
              this.$modal.msgError("执行失败,请查看日志");
            }
            this.$emit("submitted", res);
          }).finally(() => {
            this.submitButtonLoading = false;
            loading.close();
          });
        }
      },
    }
  };
</script>
